<template>
  <div class="historical-chat-list">
    <div
      class="group"
      v-for="(group, name) in filteredGroupedChatHistories"
      :key="name"
    >
      <span v-if="name === 'today'">今天</span>
      <span v-else-if="name === 'yesterday'">昨天</span>
      <span v-else-if="name === 'lastWeek'">一周内</span>
      <span v-else>更早</span>
      <div
        @click="selectChat(chat)"
        class="item"
        :class="{
          'click-menu':
            !chat.isDisabled ||
            (menuVisible && chat.chatHistoryId === selectMenuChatId),
          active: chat.chatHistoryId === selectChatId,
        }"
        v-for="chat in group"
        :key="chat.chatHistoryId"
      >
        <input
          :ref="'chatInput' + chat.chatHistoryId"
          :disabled="chat.isDisabled"
          @keyup.enter="enterInput(chat)"
          @blur="confirmInput(chat)"
          class="text"
          v-model="chat.chatTitle"
        />
        <el-dropdown
          @click.native.stop
          trigger="click"
          @visible-change="handleDropdownVisibility"
        >
          <span class="el-dropdown-link">
            <svg-icon
              class="op"
              @click="openMenu(chat)"
              icon-file-name="ellipsis"
            ></svg-icon>
          </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              icon="el-icon-edit"
              @click.native="renameChat(chat)"
              >重命名</el-dropdown-item
            >
            <el-dropdown-item
              icon="el-icon-delete"
              @click.native="deleteChat(chat.chatHistoryId)"
              >删除</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<script>
import { updateChatHistory, deleteChatHistory } from "../../../api/AIChatView";
import moment from "moment"; // 日期处理库
export default {
  props: {
    historyChatDatas: {
      type: Array,
      default: () => [],
    },
    isNewChat: {
      type: Boolean,
      default: false,
    },
    currentChatHistoryId: {
      type: Number,
      default: null,
    },
  },
  data() {
    return {
      // 菜单是否打开
      menuVisible: false,
      // 点击菜单时选择的聊天记录ID
      selectMenuChatId: null,
      // 输入框是否禁用
      isDisabled: true,
      // 点击选择的聊天记录
      selectChatId: null,
    };
  },
  methods: {
    // 点击选择聊天记录
    selectChat(chat) {
      this.selectChatId = chat.chatHistoryId;
      this.$emit("selectChat", chat);
    },
    // 打开重命名和删除的小菜单
    openMenu(chat) {
      chat;
      this.menuVisible = true;
      this.selectMenuChatId = chat.chatHistoryId;
    },
    // 监听ElementUI的下拉菜单
    handleDropdownVisibility(visible) {
      if (visible) {
        // console.log('Dropdown is opened');
      } else {
        this.menuVisible = false;
        this.selectMenuChatId = null;
      }
    },
    // 重命名
    renameChat(chat) {
      chat.isDisabled = false;
      this.$nextTick(() => {
        setTimeout(() => {
          const inputElement = this.$refs["chatInput" + chat.chatHistoryId][0];
          if (inputElement) {
            inputElement.focus();
          }
        }, 0);
      });
    },
    // 失去焦点
    confirmInput(chat) {
      chat.isDisabled = true;
      // 这里可以添加确认输入的逻辑，例如发送请求保存更改
    },
    // 回车修改标题
    enterInput(chat) {
      // console.log(chat);
      updateChatHistory({
        chatTitle: chat.chatTitle,
        chatHistoryId: chat.chatHistoryId,
      }).then((res) => {
        if (res.data.code === 1) {
          chat.isDisabled = true;
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
          });
        } else {
          this.$message.error("网络错误");
        }
      });
    },
    // 删除
    deleteChat(chatHistoryId) {
      this.$confirm("此操作将删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteChatHistory(chatHistoryId).then((res) => {
            if (res.data.code === 1) {
              // 找到这条记录并把它删除
              this.$emit("deleteChatHistory", chatHistoryId);
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
              });
            } else {
              this.$message.error("网络错误");
            }
          });
        })
        .catch(() => {
          this.$notify.info({
            title: "消息",
            message: "已取消删除",
          });
        });
    },
  },
  computed: {
    // 根据日期过滤并分组聊天记录
    filteredGroupedChatHistories() {
      const grouped = {
        today: [],
        yesterday: [],
        lastWeek: [],
        older: [],
      };

      this.historyChatDatas.forEach((chat) => {
        const chatDate = moment(chat.chatDate);
        const today = moment();
        const yesterday = moment().subtract(1, "days");
        const lastWeek = moment().subtract(7, "days");

        if (chatDate.isSame(today, "day")) {
          grouped.today.push(chat);
        } else if (chatDate.isSame(yesterday, "day")) {
          grouped.yesterday.push(chat);
        } else if (chatDate.isAfter(lastWeek)) {
          grouped.lastWeek.push(chat);
        } else {
          grouped.older.push(chat);
        }
      });

      return Object.keys(grouped).reduce((acc, key) => {
        if (grouped[key].length > 0) {
          acc[key] = grouped[key];
        }
        return acc;
      }, {});
    },
  },
  watch: {
    isNewChat(newVal) {
      if (newVal) {
        this.selectChatId = null;
      }
    },
    currentChatHistoryId(newVal) {
      this.selectChatId = newVal;
    },
  },
};
</script>

<style lang="less" scoped>
.historical-chat-list {
  margin-top: 10px;
  max-height: 400px;
  overflow-y: auto;
  .group {
    padding: 10px;
    box-sizing: border-box;
    &::-webkit-scrollbar {
      width: 3px;
    }

    &::-webkit-scrollbar-track {
      background: #f0f0f0; /* 确保这里的颜色是你想要的 */
      border-radius: 5px;
    }

    &::-webkit-scrollbar-thumb {
      border-radius: 10px;
      background: #888;
    }

    &::-webkit-scrollbar-thumb:hover {
      background: #555;
    }
    span {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
      font-size: 12px;
      color: rgb(125, 125, 125);
    }
    .item {
      cursor: pointer;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border-radius: 5px;
      padding: 7px;
      line-height: 25px;
      &:hover,
      &.click-menu,
      &.active {
        background-color: #dedede;
        svg {
          display: block;
          color: #000;
        }
      }
      .text {
        width: 90%;
        font-size: 14px;
        border: none;
        background-color: transparent;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        line-height: 25px;
        // 解决禁用无法点击的bug
        pointer-events: none;
      }
      .text:focus {
        border: none;
        outline: none;
        border-bottom: 1px solid #ccc;
      }
      .text {
        color: black;
      }
      svg {
        cursor: pointer;
        display: none;
        width: 20px;
        height: 20px;
      }
    }
  }
}
</style>

<style scoped>
.el-dropdown-menu__item:not(.is-disabled):hover {
  background-color: #f5f7fa;
  color: #000;
}
</style>